package javabase.demo02;

import java.util.*;

public class SetPractice {
    public static void main(String[] args) {
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Orange");
        hashSet.add("Apple"); // 重复元素，不会被添加
        System.out.println("HashSet: " + hashSet);
        System.out.println("包含Apple? " + hashSet.contains("Apple"));

        // 遍历HashSet
        System.out.println("=== 遍历HashSet ===");
        for (String fruit : hashSet) {
            System.out.println(fruit);
        }

        // LinkedHashSet - 维护插入顺序
        Set<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("First");
        linkedHashSet.add("Second");
        linkedHashSet.add("Third");
        linkedHashSet.add("First"); // 重复

        System.out.println("LinkedHashSet: " + linkedHashSet);

        // TreeSet - 基于TreeMap，有序
        Set<String> treeSet = new TreeSet<>();
        treeSet.add("Orange");
        treeSet.add("Apple");
        treeSet.add("Banana");

        System.out.println("TreeSet(自然排序): " + treeSet);

        // 自定义排序
        Set<String> reverseTreeSet = new TreeSet<>(Comparator.reverseOrder());
        reverseTreeSet.add("Orange");
        reverseTreeSet.add("Apple");
        reverseTreeSet.add("Banana");

        System.out.println("TreeSet(逆序): " + reverseTreeSet);

        // 对象去重示例
        demonstrateObjectDeduplication();
    }

    // 演示对象如何正确实现去重
    private static void demonstrateObjectDeduplication() {
        System.out.println("\n=== 对象去重演示 ===");

        // 未正确实现equals和hashCode的类
        Set<BadStudent> badStudents = new HashSet<>();
        badStudents.add(new BadStudent(1, "Alice"));
        badStudents.add(new BadStudent(1, "Alice")); // 应该去重但不会

        System.out.println("BadStudent去重失败: " + badStudents.size());

        // 正确实现equals和hashCode的类
        Set<GoodStudent> goodStudents = new HashSet<>();
        goodStudents.add(new GoodStudent(1, "Alice"));
        goodStudents.add(new GoodStudent(1, "Alice")); // 成功去重

        System.out.println("GoodStudent成功去重: " + goodStudents.size());
    }
}

// 未正确实现equals和hashCode的类
class BadStudent {
    private int id;
    private String name;

    public BadStudent(int id, String name) {
        this.id = id;
        this.name = name;
    }

    // 缺少equals和hashCode方法
}

// 正确实现equals和hashCode的类
class GoodStudent {
    private int id;
    private String name;

    public GoodStudent(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GoodStudent that = (GoodStudent) o;
        return id == that.id && Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}